package com.gin.no_gay_alliance.fragment.post.emote;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.no_gay_alliance.databinding.FragmentEmoteGroupBinding;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.viewmodel.emote.EmoteGroupModel;
import com.gin.no_gay_alliance.viewmodel.emote.EmoteModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 显示一个表情组内表情的Fragment
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/27 19:36
 **/
public class EmoteGroupFragment extends BaseBindingFragment<FragmentEmoteGroupBinding> {
    /**
     * 每页表情个数
     */
    int size = 12;
    /**
     * 表情分页
     */
    List<ArrayList<EmoteModel>> emotePages;

    @Override
    protected void onCreateView() {

        Bundle arguments = getArguments();
        if (arguments == null) {
            throw new RequireParamException();
        }

        EmoteGroupModel emoteGroupModel = arguments.getParcelable(EmoteGroupModel.class.getName());
        if (emoteGroupModel == null) {
            throw new RequireParamException();
        }
        // 将分组内的表情分页
        emotePages = new ArrayList<>();
        ArrayList<EmoteModel> emotes = emoteGroupModel.emotes;
        for (int i = 0; i < emotes.size(); i += size) {
            emotePages.add(new ArrayList<>(emotes.subList(i, Math.min(i + size, emotes.size()))));
        }


        b.tvPage.setText(String.valueOf(1));
        // 表情分页
        b.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                EmotePageFragment fragment = new EmotePageFragment();
                Bundle args = new Bundle();
                args.putParcelableArrayList(EmoteModel.class.getName(), emotePages.get(position));
                fragment.setArguments(args);
                return fragment;
            }

            @Override
            public int getItemCount() {
                return emotePages == null ? 0 : emotePages.size();
            }
        });

        b.tvTotalPage.setText(String.valueOf(emotePages.size()));

        b.vp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                b.tvPage.setText(String.valueOf(position + 1));
            }
        });
    }


    public static EmoteGroupFragment newInstance(EmoteGroupModel emoteGroup) {
        EmoteGroupFragment fragment = new EmoteGroupFragment();
        Bundle args = new Bundle();
        args.putParcelable(EmoteGroupModel.class.getName(), emoteGroup);
        fragment.setArguments(args);
        return fragment;
    }

}
